package com.nf.health.app.homepage.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.ViewHolder;
import com.nf.health.app.customview.MyExpandableListView;
import com.nf.health.app.models.AppraisalQuestion;
import com.nf.health.app.models.Praise;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 中医在线——风险评估
 * @author jiax
 *
 */
public class RiskEvaluationActivity extends BaseActivity {

	private MyExpandableListView lv_expandable;
	private EditText et_username;
	private EditText et_phonenum;
	private EditText et_msg;
	private Button btn_submit;
	private List<AppraisalQuestion> questions;
	/**
	 * 存储答案id的集合，List的position表示各检测项目的顺序，每个SparseArray表示对应检测项目下的题目id——答案id 的键值对。
	 */

	List<Integer> mlist;
	List<Integer> mlist2;
	private Map<String, String> isCheckMap = new HashMap<String, String>();
	private MyExpandableAdapter myExpandableAdapter;
	private View ll_content;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setTitleBar(R.layout.titlebar_base);
		ViewUtil.setText(this, R.id.titlebar_title_tv, "风险评估");
		setContent(R.layout.activity_risk_evaluation);

		mlist = new ArrayList<Integer>();
		mlist2 = new ArrayList<Integer>();

		initView();

		provider.requestRiskEvaluation("risk");
	}

	private void initView() {
		ll_content = ViewUtil.getView(this, R.id.ll_content);
		lv_expandable = ViewUtil.getView(this, R.id.lv_expandable);
		et_username = ViewUtil.getView(this, R.id.et_username);
		et_phonenum = ViewUtil.getView(this, R.id.et_phonenum);
		et_msg = ViewUtil.getView(this, R.id.et_msg);
		btn_submit = ViewUtil.getView(this, R.id.btn_submit);
		TextView titlebar_right_tv = ViewUtil.getView(this, R.id.titlebar_right_tv);
		titlebar_right_tv.setVisibility(View.VISIBLE);
		titlebar_right_tv.setText("历史记录");
		titlebar_right_tv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO 体检记录
				Bundle bundle = new Bundle();
				bundle.putString("type", "major");
				ActivityUtils.showActivity(RiskEvaluationActivity.this, DetectionHistoryListActivity.class, bundle);
			}
		});
		lv_expandable.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				String keyid = questions.get(groupPosition).getQnumber();
				Map<String, String> answerMap = questions.get(groupPosition).getAnswer().get(childPosition);
				for(Map.Entry<String, String> entry : answerMap.entrySet()){
					String answerid = entry.getKey();
					isCheckMap.put(keyid, answerid);
				}

				myExpandableAdapter.notifyDataSetChanged();				
				return false;
			}
		});

		btn_submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String username = et_username.getText().toString();
				String phonenum = et_phonenum.getText().toString();
				String message = et_msg.getText().toString();

				if(TextUtils.isEmpty(username) || TextUtils.isEmpty(phonenum)){
					showToast("姓名或电话为空");
					return;
				}
				if(isCheckMap.size() != 0){
					if(isCheckMap.size() != questions.size()){
						Set<String> bb = isCheckMap.keySet();//所有题数

						mlist.clear();
						mlist2.clear();

						for (int i = 1; i < questions.size()+1; i++) {
							if(bb.contains(i+"")){//32中是否包含  1~32
								if(mlist2.contains(i)){
								}else{
									mlist.add(i);
								}
							}else{
								mlist2.add(i);//未
							}
						}
						showToast("您第"+mlist2.get(0)+"题未回答");
						return;
					}
				}else{
					showToast("您还没有答题");
					return;
				}
				String json = new Gson().toJson(isCheckMap);
				provider.requestCommitPingGuDetail(json, username, phonenum, message, "commitDetail");
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public void handleActionSuccess(String actionName, Object object) {
		if("risk".equals(actionName)){
			questions = (List<AppraisalQuestion>)object;
			myExpandableAdapter = new MyExpandableAdapter();
			lv_expandable.setAdapter(myExpandableAdapter);
			et_username.setText(PreferenceHelper.getString(PreferenceHelper.USERNICK, ""));
			et_phonenum.setText(PreferenceHelper.getString(PreferenceHelper.USERNAME, ""));
			ll_content.setVisibility(View.VISIBLE);
		}else if("commitDetail".equals(actionName)){
			List<Praise> praises = (List<Praise>)object;
			if(praises.size()>0){
				Bundle bundle = new Bundle();
				bundle.putString("majorid", praises.get(0).getMajor_id());
				ActivityUtils.showActivityForResult(this, DoctorSelectedActivity.class, bundle, 100);
			}
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==100 && resultCode == RESULT_OK){
			finish();
		}
	}

	class MyExpandableAdapter extends BaseExpandableListAdapter{

		@Override
		public int getGroupCount() {
			return questions == null ? 0 : questions.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			List<Map<String, String>> answers = questions.get(groupPosition).getAnswer();
			return answers == null ? 0 : answers.size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return questions.get(groupPosition);
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return questions.get(groupPosition).getAnswer().get(childPosition);
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			ViewHolder holder = ViewHolder.get(parent, convertView, R.layout.item_risk_evaluation, groupPosition);
			holder.setText(R.id.tv_question_title, (groupPosition+1)+". "+questions.get(groupPosition).getTitle());
			lv_expandable.expandGroup(groupPosition);
			return holder.getConvertView();
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			ViewHolder holder = ViewHolder.get(parent, convertView, R.layout.item_evaluation_answer, childPosition);
			CheckBox tv_title = holder.getView(R.id.tv_title);
			Map<String, String> answerMap = (Map<String, String>) getChild(groupPosition, childPosition);
			AppraisalQuestion question = (AppraisalQuestion) getGroup(groupPosition);
			for(Map.Entry<String, String> entry : answerMap.entrySet()){
				if(entry.getKey().equals(isCheckMap.get(question.getQnumber()))){
					tv_title.setChecked(true);
				}else{
					tv_title.setChecked(false);
				}
				tv_title.setText(entry.getValue());
			}
			return holder.getConvertView();
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			/*
			 * 很重要：实现ChildView点击事件，必须返回true
			 * 子布局需要加：android:descendantFocusability="blocksDescendants"
			 */ 
			return true;
		}

	}
}
